package com.guchenbo.scala.c5

import com.guchenbo.scala.Helper

import scala.collection.mutable.ArrayBuffer


/**
 * @author guchenbo
 * @date 2022/3/16
 */
object ArrayDemo {
  def main(args: Array[String]): Unit = {
    //    new创建
    val arr: Array[Int] = new Array[Int](5)
    //    使用object创建
    val ints = Array[Int](1, 2, 3, 4, 5)

    arr(0) = 1
    arr(1) = 2
    println(arr(2))
    println(arr.mkString(","))

    Helper.div()

    //    后面加
    val arr2 = arr.:+(5)
    println(arr2.mkString(","))
    //    前面加
    val arr3 = arr.+:(6)
    println(arr3.mkString("(", ",", ")"))

    Helper.div()
    //    简写
    val arr4 = arr :+ 5
    val arr5 = 2 +: arr
    println(arr4.mkString(","))
    println(arr5.mkString(","))

    Helper.div()
    val ab = new ArrayBuffer[Int](16)
    val ab2 = ArrayBuffer[Int](1, 2, 3, 4, 5)
    println(ab)
    println(ab2)
    ab2 += 2
    val ab3 = ab2 += 4
    println(ab2)
    println(ab2 == ab3) // true

    //    后面加
    ab2 += 5
    //    前面加
    1 +=: ab2
    println(ab2)

    Helper.div()
    //    可变推荐用方法
    ab2.append(6)
    ab2.prepend(1)
    println(ab2)
    Helper.div()

    ab2.remove(1)
    println(ab2)


    //    可变和不可变的转换
    val ab1 = ArrayBuffer(1, 2, 3, 4, 5)
    val arr1 = ab1.toArray
    val arb = arr1.toBuffer
    Helper.div()
    println(ab1)
    println(arr1.mkString)
    ab1.append(6)
    println(arb)
    println(arb == ab1)

    Helper.div()
    //    多维数组
    val dim: Array[Array[Int]] = Array.ofDim(3, 4)
    dim(0)(1) = 1
    dim(1)(2) = 2

    for (i <- dim.indices; j <- dim(i).indices) println(dim(i)(j))
    Helper.div()
    for (i <- dim.indices; j <- dim(i).indices) {
      print(dim(i)(j) + "\t")
      if (j == dim(i).length - 1) println
    }
    Helper.div()
    dim.foreach(_.foreach(println))


  }
}
